package cn.com.dcsgo.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 拦截器
 * 类似于 JavaEE中的Filter，但是控制粒度更细
 * 并且是SpringMVC中的一部分
 *
 * @author Dcsgo
 * @since 2025/3/5 9:26
 */

public class MyHandlerInterceptor implements HandlerInterceptor {
    /**
     * 在调用handler之前调用该方法
     * 可以进行编码转换、登录保护、权限效验等
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  chosen handler to execute, for type and/or instance evaluation
     * @return true表示放行，false表示拦截
     * @throws Exception Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyHandlerInterceptor.preHandle");
        return true;
    }

    /**
     * 在handler返回后调用该方法，可以对返回的结果进行处理
     * 例如敏感词过滤
     *
     * @param request      current HTTP request
     * @param response     current HTTP response
     * @param handler      handler
     * @param modelAndView 返回的视图和共享域数据对象
     * @throws Exception Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyHandlerInterceptor.postHandle");
    }

    /**
     * 在dispatcherServlet即将响应客户端之前调用该方法，也就是完成了所有的处理工作后
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  handler
     * @param ex       ex
     * @throws Exception Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyHandlerInterceptor.afterCompletion");
    }
}
